package com.myapp.entity.proxy;

import java.util.List;

import com.myapp.data.define.BaseBean;
import com.myapp.entity.proxy.database.DBProxy;
import com.myapp.entity.proxy.interfaces.IProxy;
import com.myapp.entity.proxy.mem.MemProxy;

public class EntityProxy implements IProxy {

	private static EntityProxy entityProxy = null;

	private EntityProxy() {
	}

	public static EntityProxy getInstance() {
		if (entityProxy == null) {
			entityProxy = new EntityProxy();
		}
		return entityProxy;
	}

	
	// 数据代理层
	private IProxy dbProxy = new DBProxy();

	// 其他数据获取代理链表
	private IProxy[] proxyLayers = new IProxy[] { new MemProxy() };

	@Override
	public int insert(BaseBean entity) throws Exception {
		int dbInsert = dbProxy.insert(entity);
		if (dbInsert > 0) {
			for (IProxy proxy : proxyLayers) {// 循环插入，其他缓冲层
				proxy.insert(entity);
			}
		}
		return dbInsert;
	}

	@Override
	public <T extends BaseBean> int update(T entity) throws Exception {
		int dbUpdate = dbProxy.update(entity);
		if (dbUpdate > 0) {
			for (IProxy proxy : proxyLayers) {// 循环更新
				dbUpdate = proxy.update(entity);
			}
		}
		return dbUpdate;
	}

	@Override
	public <T extends BaseBean> int delete(T entity) throws Exception {
		int dbDelete = dbProxy.delete(entity);
		if (dbDelete > 0) {
			for (IProxy proxy : proxyLayers) {// 循环更新
				dbDelete = proxy.delete(entity);
			}
		}
		return dbDelete;
	}

	@Override
	public <T extends BaseBean> T get(long id, Class<T> clazz) throws Exception {
		T entity = null;
		for (IProxy proxy : proxyLayers) {// 循环在层中寻找
			entity = proxy.get(id, clazz);
			if (entity != null) {
				break;
			}
		}

		// 如果没有找到就从数据库中找
		if (entity == null) {
			entity = dbProxy.get(id, clazz);
			// 循环更新缓冲层
			for (IProxy proxy : proxyLayers) {
				proxy.insert(entity);
			}
		}

		return entity;
	}

	@Override
	public <T extends BaseBean> List<T> findAllByUid(long uid, Class<T> clazz)
			throws Exception {
		List<T> datas = null;
		for (IProxy proxy : proxyLayers) {// 循环在层中寻找
			datas = proxy.findAllByUid(uid, clazz);
			if (datas != null) {
				break;
			}
		}

		// 如果没有找到就从数据库中找
		if (datas == null) {
			datas = dbProxy.findAllByUid(uid, clazz);
		}

		return datas;
	}
}
